import asyncio
import json
import sys
from pathlib import Path
from playwright.async_api import async_playwright

SAVE_PATH = Path(__file__).resolve().parent / "cookies" / "myxhs.json"
print(SAVE_PATH)

from wxauto import WeChat

# 初始化微信实例
wx = WeChat()

async def check_login(wx_who="文件传输助手"):
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=False)
        context = await browser.new_context()
        page = await context.new_page()
        # 优先尝试加载本地cookies和user_agent
        if SAVE_PATH.exists():
            with open(SAVE_PATH, "r", encoding="utf-8") as f:
                data = json.load(f)
            cookies = data.get("cookies", [])
            user_agent = data.get("user_agent", None)
            if user_agent:
                await context.set_extra_http_headers({"User-Agent": user_agent})
            if cookies:
                await context.add_cookies(cookies)
        await page.goto("https://creator.xiaohongshu.com/")
        need_login = False
        await asyncio.sleep(3)
        # 10秒内页面是否跳转到登录页
        for _ in range(10):
            if page.url.startswith("https://creator.xiaohongshu.com/login"):
                need_login = True
                break
            await asyncio.sleep(1)
        if not need_login:
            print("已自动登录，无需扫码")
            await browser.close()
            return True
        if need_login:
            await page.click(".css-wemwzq")
            await asyncio.sleep(3)
            await page.wait_for_selector(".css-dvxtzn", timeout=10000)
            element = page.locator(".css-dvxtzn")
            await element.screenshot(path="captured_image.png")
            print("已保存为 captured_image.png")
            print("请扫码登录小红书创作者平台，登录后按回车继续...")
            wx.SendMsg(msg="请扫码登录小红书创作者平台，登录后按回车继续...", who=wx_who, exact=False)
            wx.SendFiles(filepath="captured_image.png", who=wx_who, exact=False)
            for sec in range(50):
                if page.url == "https://creator.xiaohongshu.com/new/home":
                    print("页面已成功跳转到 https://creator.xiaohongshu.com/new/home")
                    break
                elif sec == 49:
                    await browser.close()
                    return False
                else:
                    await asyncio.sleep(1)
            # 登录后保存cookie
            cookies = await context.cookies()
            user_agent = await page.evaluate("navigator.userAgent")
            storage = await context.storage_state()
            data = {
                "cookies": cookies,
                "user_agent": user_agent,
                "storage": storage
            }
            SAVE_PATH.parent.mkdir(parents=True, exist_ok=True)
            with open(SAVE_PATH, "w", encoding="utf-8") as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
            print(f"已保存到 {SAVE_PATH}")
            print("[DEBUG] 准备关闭浏览器")
            await browser.close()
            print("[DEBUG] 浏览器已关闭，准备 return True")
            return True

if __name__ == "__main__":
    asyncio.run(check_login())
